package com.bookstore.servlet;

import com.bookstore.entity.Page;
import com.bookstore.entity.Product;
import com.bookstore.service.ProductService;
import com.bookstore.service.impl.ProductServiceImpl;
import com.bookstore.utils.DataConsts;
import com.bookstore.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

@WebServlet("/product.do")
public class ProductServlet extends BaseServlet {
    ProductService productService = new ProductServiceImpl();

    protected void queryAll(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        List<Product> products = productService.queryAllProducts();
        req.setAttribute("products", products);
        req.getRequestDispatcher("/admin/product_list.jsp").forward(req, resp);
    }

    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Product product = new Product();
        try {
            //解析上传的数据 得到每个表单项FileItem
            List<FileItem> list = (List<FileItem>) req.getAttribute("fileList");
            //循环判断：每一个表单项是普通文本类型，还是文件类型
            for (int i = 0; i < list.size(); i++) {
                FileItem fileItem = list.get(i);
                if (fileItem.isFormField()) {
                    if ("action".equals(fileItem.getFieldName()) || "id".equals(fileItem.getFieldName())) {
                        continue;
                    }
                    //根据名称获取属性对象；反射\内省
                    Field field = product.getClass().getDeclaredField(fileItem.getFieldName());
                    System.out.println(field.getName());
                    Class<?> type = field.getType();
                    Object fieldValue = fileItem.getString("UTF-8");
                    //TODO:根据传入的字符串 转换成对应类型的Value
                    if (type.equals(Integer.class)) {
                        fieldValue = (Object) Integer.valueOf(fileItem.getString("UTF-8"));
                    } else if (type.equals(Double.class)) {
                        fieldValue = (Object) Double.valueOf(fileItem.getString("UTF-8"));
                    } else if (type.equals(Long.class)) {
                        fieldValue = (Object) Long.valueOf(fileItem.getString("UTF-8"));
                    }
                    if (field != null) {
                        field.setAccessible(true);
                        field.set(product, fieldValue);
                    }
                } else {
                    //按照当前毫秒值+文件后缀名的方式生成文件名
                    long timeMills = System.currentTimeMillis();
                    String originalFileName = fileItem.getName();
                    //1.2.jpg ==> "1"  "2"  "jpg"
                    String[] split = originalFileName.split("\\.");
                    String s = split[split.length - 1];
                    //获取当前上传文件的后缀名
                    String newFileName = new StringBuilder(s).insert(0, ".").insert(0, timeMills).toString();
                    //生成一个按照规则的文件名
                    product.setImgUrl(newFileName);
                    fileItem.write(new File(DataConsts.IMG_SAVE_LOCAL_PATH + newFileName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        int result = productService.insertProduct(product);
        //直接跳转回商品查询界面
        resp.sendRedirect("./product.do?action=queryAll");

    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Long id = Long.valueOf(req.getParameter("id"));
        String name = req.getParameter("name");
        Double price = Double.valueOf(req.getParameter("price"));
        String category = req.getParameter("category");
        Integer pNum = Integer.valueOf(req.getParameter("pNum"));
        String imgUrl = req.getParameter("imgUrl");
        String description = req.getParameter("description");
        int result = productService.updateProduct(new Product(id, name, price, category, pNum, imgUrl, description));
        System.out.println(result);
        //直接跳转回商品查询界面
        resp.sendRedirect("./product.do?action=queryAll");
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Long id = Long.valueOf(req.getParameter("id"));
        int result = productService.deleteProduct(id);
        System.out.println(result);
        //直接跳转回商品查询界面
        resp.sendRedirect("./product.do?action=queryAll");
    }

    /**
     * 处理分页功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        //1 获取请求的参数 pageNo 和 pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.DEFAULT_PAGE_SIZE);
        //2 调用GoodsService.page(pageNo，pageSize)：Page 对象
        Page<Product> page = productService.page(pageNo, pageSize);
        //3 保存Page 对象到Request 域中
        req.setAttribute("page", page);
        //4 请求转发到/admin/product_list.jsp 页面
        req.getRequestDispatcher("/admin/product_list.jsp").forward(req, resp);
    }

}
